<template>
  <el-dialog title="零工报工单审核" :visible.sync="visible" width="960px" top="5vh" append-to-body>
    <div style="text-align: right" class="dialog-footer">
      <el-button type="primary" :loading="sploading" @click="fnApprovedDbinfo" v-if="rfwork!=null && rfwork.leaderPass!='0' && isDb==='0' ">审核通过</el-button>
      <el-button type="primary" :loading="fhloading" @click="fnCheckPassDbinfo" v-if="rfwork!=null && rfwork.recheckPass!='0' && rfwork.leaderPass==='0' && isDb==='0' ">复核通过</el-button>

    </div>
    <div style="text-align: center;"><h2>零工日报表</h2></div>
    <el-divider />

    <el-table v-loading="loading" :data="oddjobList" @selection-change="handleSelectionChange">
      <el-table-column type="index" width="30" align="center" />
      <el-table-column label="出工方式" width="100" align="center" prop="wm.wmName" />
      <el-table-column label="车间" align="center" prop="slWorkshop.workshopName" />
      <el-table-column label="大工序" align="center" prop="slGprocess.gprocessName" />
      <el-table-column label="开始时间" align="center" prop="oddjobStart" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.oddjobStart, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="oddjobEnd" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.oddjobEnd, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时长" align="center" prop="oddjobDuration" />
      <el-table-column label="计薪" align="center" prop="wmPay" />
      <el-table-column fixed="right" label="操作" width="120" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button
            v-if="rfwork!=null"
            size="mini"
            type="text"
            icon="el-icon-sort-down"
            @click="handleDm(scope.row)"
          >扣款</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
          >详细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改零工报工对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="出工方式" prop="wmId">
               {{ form.wm != null ? form.wm.wmName : '' }}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计薪" prop="wmPay">
              {{form.wmPay + "元/"}}{{ sourceWmUnitFormat(form.wmUnit) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="oddjobStart">
              {{form.oddjobStart}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="oddjobEnd">
              {{form.oddjobEnd}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
           <el-form-item label="时长" prop="oddjobDuration">
             {{form.oddjobDuration}}
           </el-form-item>
          </el-col>
       </el-row>
       <el-row>
         <el-col :span="8">
           <el-form-item label="所属模块" prop="moduleId">
             {{ form.slModule != null ? form.slModule.moduleName : '' }}
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="所属车间" prop="workshopId">
              {{ form.slWorkshop != null ? form.slWorkshop.workshopName : '' }}
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="大工序" prop="gprocessId">
             {{ form.slGprocess != null ? form.slGprocess.gprocessName : '' }}
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
         <el-col :span="8">
           <el-form-item label="小工序" prop="processId">
             {{ form.slProcess != null ? form.slProcess.processName : '' }}
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="实际生产" prop="oddjobActual">
             {{form.oddjobActual}}
           </el-form-item>
         </el-col>
       </el-row>
        <el-divider content-position="center">操作人</el-divider>
        <el-table :data="slOddjobOmemberList" :row-class-name="rowSlOddjobOmemberIndex" @selection-change="handleSlOddjobOmemberSelectionChange" ref="slOddjobOmember" style="width:100%">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="操作人" prop="omemberNick" />
          <el-table-column label="职级" prop="levelName" />
          <el-table-column label="计薪方式" prop="ssmName" />
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
       <el-button v-if="rfwork!=null && isDb==='0' " type="primary" @click="handleUpdate">修改</el-button>
        <el-button @click="cancel">返 回</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改零工报工对话框 -->
         <el-dialog :title="editTitle" :visible.sync="editOpen" width="960px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="出工方式" prop="wmId">
                  <el-select v-model="form.wmId"  @change="handleGetwmPay" placeholder="请选择">
                    <el-option
                      v-for="item in wmOptions"
                      :key="item.wmId"
                      :label="item.wmName"
                      :value="item.wmId"
                      :disabled="item.status == 1"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="计薪" prop="wmPay">
                  <el-input v-model="form.wmPay" :disabled="true" placeholder="请输入计薪" >
                    <template slot="append">元/{{ sourceWmUnitFormat(form.wmUnit) }}</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="开始时间" prop="oddjobStart">
                  <el-date-picker clearable
                    v-model="form.oddjobStart"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    default-time="12:00:00"
                    placeholder="请选择开始时间"
                    @change="handleCompareTime"
                    >
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="结束时间" prop="oddjobEnd">
                  <el-date-picker clearable
                    v-model="form.oddjobEnd"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择结束时间"
                    @change="handleCompareTime"
                    >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
               <el-form-item label="时长" prop="oddjobDuration">
                 <el-input v-model="form.oddjobDuration"  class="def-input-number" type="number" placeholder="请输入时长" />
               </el-form-item>
              </el-col>
           </el-row>
           <el-row>
             <el-col :span="8">
               <el-form-item label="所属模块" prop="moduleId">
                 <el-select v-model="form.moduleId" :disabled="true" filterable @change="handleChangeModule" placeholder="请选择所属模块">
                   <el-option v-for="item in moduleOptions" :key="item.moduleId" :label="item.moduleName"
                     :value="item.moduleId" :disabled="item.status == 1"></el-option>
                 </el-select>
               </el-form-item>
             </el-col>
             <el-col :span="8">
               <el-form-item label="所属车间" prop="workshopId">
                 <el-select v-model="form.workshopId" filterable @change="handleChangeWorkshop" placeholder="请选择所属车间">
                   <el-option v-for="item in workshopOptions" :key="item.workshopId" :label="item.workshopName"
                     :value="item.workshopId" :disabled="item.status == 1"></el-option>
                 </el-select>
               </el-form-item>
             </el-col>
             <el-col :span="8">
               <el-form-item label="大工序" prop="gprocessId">
                 <el-select v-model="form.gprocessId" filterable @change="handleChangeProcess" placeholder="请选择大工序">
                   <el-option v-for="item in gprocessOptions" :key="item.gprocessId" :label="item.gprocessName"
                     :value="item.gprocessId" :disabled="item.status == 1"></el-option>
                 </el-select>
               </el-form-item>
             </el-col>
           </el-row>
           <el-row>
             <el-col :span="8">
               <el-form-item label="小工序" prop="processId">
                 <el-select v-model="form.processId" filterable placeholder="请选择小工序">
                   <el-option v-for="item in processOptions" :key="item.processId" :label="item.processName"
                     :value="item.processId" :disabled="item.status == 1"></el-option>
                 </el-select>
               </el-form-item>
             </el-col>
             <el-col :span="8">
               <el-form-item label="实际生产" prop="oddjobActual">
                 <el-input v-model="form.oddjobActual"  class="def-input-number" type="number"
                   placeholder="请输入实际生产" />
               </el-form-item>
             </el-col>
           </el-row>
            <el-divider content-position="center">零工操作人信息</el-divider>
            <el-table :data="slOddjobOmemberList" :row-class-name="rowSlOddjobOmemberIndex" @selection-change="handleSlOddjobOmemberSelectionChange" ref="slOddjobOmember" style="width:100%">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="序号" align="center" prop="index" width="50"/>
              <el-table-column label="操作人" prop="omemberNick" />
              <el-table-column label="职级" prop="levelName" />
              <el-table-column label="计薪方式" prop="ssmName" />
            </el-table>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button v-if="rfwork!=null && isDb==='0' " type="primary" @click="submitForm">保存</el-button>
            <el-button @click="cancelEdit">取 消</el-button>
          </div>
        </el-dialog>


    <!-- 扣款 -->
    <el-dialog :title="dmtitle" :visible.sync="dmopen" width="550px" append-to-body>
      <el-form ref="dmform" :model="dmform" :rules="dmrules" label-width="120px">
          <el-table :data="dmList" ref="slDm" style="width:100%">
            <el-table-column label="扣款时间" align="center" width="100px" >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.dmTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="扣款人" prop="dmNick"  />
            <el-table-column label="扣款金额" prop="dmAmount"  />
            <el-table-column label="扣款原因" prop="dmReason"  />
          </el-table>
          <el-form-item label="增加扣款金额" prop="dmAmount">
            <el-input v-model="dmform.dmAmount" class="def-input-number" type="number" placeholder="请输入金额" />
          </el-form-item>
          <el-form-item label="扣款原因" prop="dmReason">
            <el-input v-model="dmform.dmReason" type="textarea" placeholder="请输入原因" />
          </el-form-item>
      </el-form>
      <el-divider content-position="center"></el-divider>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="fnSubmitDm">提 交</el-button>
        <el-button @click="dmCancel">返 回</el-button>
      </div>
    </el-dialog>


  </el-dialog>
</template>

<script>
import {listOddjobByrfworkId,listRworkByrfworkId,listNoSubmitOddjob,listOddjob, getOddjob, delOddjob, addOddjob, updateOddjob,updateOddjobDateTime,getOddjobOptions,isUniqueJobUser,submitDateOddjobs } from "@/api/sl/oddjob";
import { approvedDbinfo,checkPassDbinfo } from "@/api/sl/dbinfo";
import { getRfwork } from "@/api/sl/rfwork";
import { listDmByRworkId,addDm } from "@/api/sl/dm";
import {getWorkshopListByModuleId} from "@/api/sl/workshop";
import {getGprocessListByWorkshopId} from "@/api/sl/gprocess";
import {getProcessListByGprocessId} from "@/api/sl/process";

export default {
  name: "Oddjobinfo",
  dicts: ['sl_rwork_class','sl_wm_unit'],
  data() {
    let watermarkContentVaild = (rule, value, callback) => {
      if (value == null || value === "") {
        callback();
      } else {
        let length = value.length
        if (length > 7) {
          callback(new Error("输入不能超过7位"))
        } else {
          callback();
        }
      }
    }
    return {
      visible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSlOddjobOmember: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 零工报工表格数据
      oddjobList: [],
      // 零工操作人表格数据
      slOddjobOmemberList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rfworkId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      moduleOptions:[],
      workshopOptions: [],
      gprocessOptions: [],
      processOptions: [],
      wmOptions:[],
      oddjobAttendanceList:[],
      source:null,
      sourceId:null,
      dbId:null,
      rfwork:{},
      dmList: [],
      dmtitle: "",
      dmform : {},
      dmopen: false,
      dmrules:{
        dmAmount: [
          { required: true, message: "扣款金额不能为空", trigger: "blur" },
          {validator: watermarkContentVaild, trigger: 'blur'}
        ],
        dmReason: [
          { required: true, message: "扣款原因不能为空", trigger: "blur" },
        ],
      },
       isDb:1,
       sploading:false,
       fhloading:false,
       editTitle: "",
       editOpen: false
    };
  },
  created() {

  },
  methods: {
    // 显示弹框
    show(dbId,source,sourceId,isDb) {
      // console.log(sourceId)
      this.source = source;
      this.sourceId = sourceId;
      this.dbId = dbId;
      this.isDb = isDb;
      this.queryParams.rfworkId = sourceId;
      getRfwork(this.sourceId).then(response => {
        this.rfwork = response.data;
      });

      this.getList();
      this.visible = true;
    },
    /** 查询零工报工列表 */
    getList() {
      this.loading = true;
      listOddjobByrfworkId(this.sourceId).then(response => {
        this.oddjobList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    cancelEdit() {
      this.editOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
       oddjobId: null,
       oddjobDate: null,
       moduleId: null,
       oddjobYear: null,
       oddjobMonth: null,
       oddjobDay: null,
       isApproved: null,
       leaderUser: null,
       oddjobStart: null,
       oddjobEnd: null,
       oddjobDuration: null,
       wmPay: null,
       estimatePay: null,
       oddjobUser: null,
       createBy: null,
       createTime: null,
       updateBy: null,
       updateTime: null,
       wmId: null,
       oddjobBz: null,
       wmUnit: null,
       rfworkId: null,
       oddjobDm: null,
       workshopId: null,
       gprocessId: null,
       processId: null,
       oddjobActual: null
      };
      this.slOddjobOmemberList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.oddjobId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
	/** 零工操作人序号 */
    rowSlOddjobOmemberIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 复选框选中数据 */
    handleSlOddjobOmemberSelectionChange(selection) {
      this.checkedSlOddjobOmember = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sl/oddjob/export', {
        ...this.queryParams
      }, `oddjob_${new Date().getTime()}.xlsx`)
    },
    // 计价单位字典翻译
    sourceWmUnitFormat(unit) {
      if(unit != null ){
        return this.selectDictLabel(this.dict.type.sl_wm_unit, unit);
      }
    },
    /** 详细按钮操作 */
    handleDetail(row) {
      this.reset();
      const oddjobId = row.oddjobId || this.ids
      getOddjob(oddjobId).then(response => {
        this.form = response.data;
        this.moduleOptions = response.modules;
        this.gprocessOptions = response.gprocesss;
        this.processOptions = response.processs;
        this.workshopOptions = response.workshops;
        this.wmOptions = response.wms;
        this.slOddjobOmemberList = response.data.slOddjobOmemberList;
        this.open = true;
        this.title = "报工单详细";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = false;
      this.editOpen = true;
      this.editTitle = "修改零工报工";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
         this.form.slOddjobOmemberList = this.slOddjobOmemberList;
          if (this.form.oddjobId != null) {
            updateOddjob(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.editOpen = false;
              this.getList();
            });
          }
        }
      });
    },
    // 扣款取消按钮
    dmCancel() {
      this.dmopen = false;
      this.dmform = {};
      this.dmList = [];
    },
    //扣款操作
    handleDm(row){
      const oddjobId = row.oddjobId
      listDmByRworkId(oddjobId,this.sourceId).then(response=>{
        console.log(response.data)
        this.dmList = response.data;
        this.dmtitle = "扣款";
        this.dmopen = true;
        this.dmform.rworkId = oddjobId;
      })
    },
    //扣款提交
    fnSubmitDm(){
      this.$refs["dmform"].validate(valid => {
        if (valid) {
          this.dmform.rfworkId = this.sourceId;
          addDm(this.dmform).then(response => {
            this.$modal.msgSuccess("扣款成功");
            this.dmform = {};
            this.dmList = [];
            this.dmopen = false;
          });
        }
      });
    },
    //领导审核通过
    fnApprovedDbinfo() {
      this.sploading = true;
      approvedDbinfo(this.dbId).then(response => {
        this.$emit('onApprove');
        this.visible = false;
        this.sploading = false;
      });
    },
    //复核人通过
    fnCheckPassDbinfo() {
      this.fhloading = true;
      checkPassDbinfo(this.dbId).then(response => {
        this.$emit('onApprove');
        this.visible = false;
        this.fhloading = false;
      });
    },
    //获取出工方式计价
    handleGetwmPay(value){
      for (let i = 0; i < this.wmOptions.length; i++) {
        if (this.wmOptions[i].wmId === value) {
          this.form.wmPay = this.wmOptions[i].wmPay;
          this.form.wmUnit = this.wmOptions[i].wmUnit;
          //this.handleCountPay()
          break;
        }
      }
    },
    //比较时间
    handleCompareTime(){
      if (this.form.oddjobStart && this.form.oddjobEnd) {
        let difference = new Date(this.form.oddjobEnd) - new Date(this.form.oddjobStart);
        this.form.oddjobDuration = (difference / 3600000).toFixed(2)
        //this.handleCountPay()
      } else {
        this.form.oddjobDuration = null;
      }
    },
    //模块变更查询车间
    handleChangeModule(value) {
      //清空车间
      this.form.workshopId = null;
      this.workshopOptions = [];
      //清空大工序
      this.form.gprocessId = null;
      this.gprocessOptions = [];
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getWorkshopListByModuleId(value).then(response => {
        this.workshopOptions = response.data;
      });
    },
    //车间变更查询大工序
    handleChangeWorkshop(value) {
      //清空大工序
      this.form.gprocessId = null;
      this.gprocessOptions = [];
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getGprocessListByWorkshopId(value).then(response => {
        this.gprocessOptions = response.data;
      });
    },
    //大工序变更查询小工序
    handleChangeProcess(value) {
      //清空小工序
      this.form.processId = null;
      this.processOptions = [];
      //工序单价
      this.form.processPay = null;
      getProcessListByGprocessId(value).then(response => {
        this.processOptions = response.data;
      });
    },
    userSelected(rows){
      if(rows !=null){
        rows.forEach(user => {
          let obj = {};
          obj.omemberUser = user.userName;
          obj.omemberNick = user.nickName;
          obj.levelId = user.levelId;
          obj.ssmId = user.ssmId;
          obj.levelName = user.level.levelName;
          obj.ssmName = user.ssm.ssmName;

          if(isUniqueJobUser(this.slOddjobOmemberList,obj)){
            this.slOddjobOmemberList.push(obj);
          }
        })
      }
    },
  }
};
</script>
